<template>
  <div class="department-user">
    <el-dialog
      title="部门人员管理"
      :visible.sync="dialogVisible"
      :before-close="handleClose"
      width="60%"
    >
      <el-card class="box-card" v-loading="loading">
        <div slot="header" class="clearfix">
          <span>人员列表</span>
        </div>
        <div style="margin-bottom: 6px">
          【{{ rowDataCom.dt_name }}】(<span style="color:red">{{ userDataList.length }}人</span>)
        </div>
        <div class="user-list">
          <draggable v-model="userDataList" ghostClass="ghost" chosenClass="chosen" @end="handleDragUser">
              <transition-group>
                <el-tag
                  :key="index"
                  v-for="(item, index) in userDataList"
                  size="small"
                  style="margin-bottom: 4px; cursor: pointer; margin-left:4px"
                  :disable-transitions="false"
                  @close="removeUser(item)"
                >
                  {{ item.first_name }}
                </el-tag>
              </transition-group>
          </draggable>
          <el-button
            size="mini"
            icon="el-icon-plus"
            @click="dialogUsersVisible = true"
            >加入</el-button
          >
          <el-button
            size="mini"
            icon="el-icon-refresh-left"
            @click="handleUpdateGroupSort"
            >排序刷新</el-button
          >
        </div>
      </el-card>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="handleClose"
          >确 定</el-button
        >
      </span>
    </el-dialog>
    <!-- 群组人员选择对话框 -->
    <el-dialog
      :title="`选择群组人员`"
      width="70%"
      :close-on-click-modal="false"
      :visible.sync="dialogUsersVisible"
      append-to-body
    >
      <user-manager
        ref="userManager"
        :userOuter="false"
        :shareGroup="false"
        :onSelectUsers="handleSelectShareUser"
      />
    </el-dialog>
  </div>
</template>
<script>
import { patchUserDepartment, patchUpdateUser, updateDepartmentOrderSort } from '@/api/user.js'
// 导入draggable组件
import draggable from 'vuedraggable'
export default {
  name: "PeopleManger",
  components: {
    UserManager: () =>
      import("@/views/markSys/taskCenter/components/userManager"),
    draggable
  },
  data() {
    return {
      loading: false,
      rowDataCom: {},
      userDataList: [],
      dialogUsersVisible: false,
    };
  },
  watch: {
    rowData(val) {
      if (val) {
        this.rowDataCom = val;
        this.userDataList = val.user_department.filter(item => item.first_name);
      }
    },
  },
  props: {
    dialogVisible: {
      type: Boolean,
    },
    handleClose: Function,
    rowData:null,
  },
  methods: {
    /**
     * 获取选择人员列表，更新群组人员信息
     */
    async handleSelectShareUser(selectedUsers) {
      const uniqueUsers = this.uniqueArray([
        ...this.userDataList,
        ...selectedUsers,
      ]);
      const userIds = uniqueUsers.map((item) => item.id);
      const result = await patchUserDepartment(this.rowDataCom.id, {
        user_department: userIds,
      });
      if (result) {
          this.$message.success(`添加部门人员成功`);
        }
      this.userDataList = uniqueUsers;
      this.$refs.userManager.clearSelect()
      this.dialogUsersVisible = false;
      // this.fetchShareGroupList();
    },
    //拖拽结束事件
    async handleDragUser(e) {
      // if(this.userDataList.length === 1) return
      // const {newIndex} = e
      // const moveUser = this.userDataList[newIndex]

      // if(newIndex === 0) {
      //   const {order} = this.userDataList[newIndex + 1]
      //   moveUser.order = order + 1
      // } else{
      //   const {order}= this.userDataList[newIndex - 1]
      //   moveUser.order = order - 1
      //   // if(order !== 0) {
      //   // } else {
      //   //   moveUser.order = 0
      //   // }
      // }
      // const {id, order} = moveUser
      // await patchUpdateUser(id, { order })
    },
    // 更新部门order 并刷新
     async handleUpdateGroupSort() {
      if(this.userDataList.length === 1) return
      this.loading = true
      const ids = this.userDataList.map(item => item.id)
      await updateDepartmentOrderSort({id: ids})
      this.loading = false
    },
    uniqueArray(list = []) {
      let res = list.filter(function (item, index, self) {
        return self.findIndex((el) => el.id == item.id) === index;
      });
      return res;
    },
  },
};
</script>
<style lang="scss">
.department-user {
  .el-tag + .el-tag {
    margin-left: 10px;
  }
  .no-select-group {
    text-align: center;
    padding: 24px 0;
  }
  .user-list {
    border: 1px solid #eee;
    padding: 14px 8px;
     .chosen{
      background-color: red !important;
      color: #fff;
    }
    .ghost{
      background-color: red !important;
    }
  }
  .pending-remove {
    margin-top: 10px;

    .title,
    .users {
      margin-bottom: 6px;
    }
  }
}
</style>